import time
import uiautomator2 as u2

# 连接手机
device = u2.connect()

# 颜色
red = '#c72b6a'
blue = '#6c4fcd'

# 计数器
count = 0

# 总数存储
total = []
for i in range(25):
    total.append(0)

# 状态
TIMETOCOUNT = 1 # 计算时间
WAITRESULT = 2  # 等待结果
WAITSATTLE = 3  # 等待结算

# 当前状态
current = TIMETOCOUNT

# 将RGB颜色转换为十六进制颜色
def getHexColor(pixel_color):
    return "#{:02x}{:02x}{:02x}".format(pixel_color[0], pixel_color[1], pixel_color[2])

# 区域 1 的坐标集
m1 = [
    (265, 340), (333, 340), (400, 340), (466, 340), (540, 340),
    (265, 410), (333, 410), (400, 410), (466, 410), (540, 410),
    (265, 480), (333, 480), (400, 480), (466, 480), (540, 480),
    (265, 550), (333, 550), (400, 550), (466, 550), (540, 550),
    (265, 620), (333, 620), (400, 620), (466, 620), (540, 620)
]

# 区域 2 的坐标集
m2 = [
    (255, 765), (321, 765), (387, 765), (453, 765), (519, 765),
    (255, 835), (321, 835), (387, 835), (453, 835), (519, 835),
    (255, 905), (321, 905), (387, 905), (453, 905), (519, 905),
    (255, 975), (321, 975), (387, 975), (453, 975), (519, 975),
    (255, 1045), (321, 1045), (387, 1045), (453, 1045), (519, 1045)
]

# 点击位置
click_pos = {
    '0': (248, 1368),
    '1': (128, 1529),
    '2': (344, 1529),
    '3': (560, 1529),
    '4': (767, 1529),
    '5': (977, 1529),
    '6': (247, 1680),
    '7': (463, 1680),
    '8': (679, 1680),
    '9': (880, 1680),
}

# 主循环
while True:
    time.sleep(1)
    # 截取屏幕截图并加载到内存中
    image = device.screenshot()
    if current == TIMETOCOUNT:
        print('当前状态：计算中...')
        # 初始化
        count = 0
        for i in range(25):
            total[i] = 0

        # 主循环
        for i in range(25):
            c1 = image.getpixel(m1[i])
            c2 = image.getpixel(m2[i])
            if getHexColor(c1) == red or getHexColor(c2) == blue:
                total[i] = 1

        # 计算结果
        count = total.count(1)
        print('当前状态：计算完成，结果为：', count)

        # 模拟点击
        for i in str(count):
            device.click(click_pos[i][0], click_pos[i][1])
            time.sleep(0.5)

        # 切换状态
        current = WAITRESULT

    elif current == WAITRESULT:
        print('当前状态：等待结果...')
        if (getHexColor(image.getpixel((750, 680))) != '#f2f2f2'):
            current = WAITSATTLE

    elif current == WAITSATTLE:
        print('当前状态：等待结算...')
        if (getHexColor(image.getpixel((750, 680))) == '#f2f2f2'):
            current = TIMETOCOUNT